"""
后台任务服务
"""
import asyncio
import threading
import time
from datetime import datetime
from typing import Dict, Any
from services.system_monitor import SystemMonitorService
from services.metrics_storage import MetricsStorageService
from core.config import get_settings
from core.logger import get_logger

logger = get_logger(__name__)
settings = get_settings()

class BackgroundTaskService:
    """后台任务服务"""
    
    def __init__(self):
        self._running = False
        self._thread = None
        self._metrics_thread = None
        self._cleanup_thread = None
    
    def start(self):
        """启动后台任务"""
        if self._running:
            return
        
        self._running = True
        
        # 启动系统监控数据收集任务
        self._metrics_thread = threading.Thread(target=self._metrics_collector, daemon=True)
        self._metrics_thread.start()
        
        # 启动清理任务
        self._cleanup_thread = threading.Thread(target=self._cleanup_worker, daemon=True)
        self._cleanup_thread.start()
        
        logger.info("后台任务服务已启动")
    
    def stop(self):
        """停止后台任务"""
        self._running = False
        logger.info("后台任务服务已停止")
    



    def _metrics_collector(self):
        """系统监控数据收集器"""
        logger.info("系统监控数据收集器已启动")
        monitor_times = 0
        # 保存数据库的监控次数间隔
        save_interval = int(settings.metrics_collection_interval / settings.metrics_monitor_interval)
        while self._running:
            try:
                # 获取并缓存系统指标
                metrics = SystemMonitorService.get_current_metrics(settings.metrics_monitor_interval)
                monitor_times += 1
                SystemMonitorService.set_cached_metrics(metrics)
                if save_interval == monitor_times:
                    monitor_times = 0
                    logger.info(f"系统监控指标: CPU={metrics['cpu_percent']}%, "
                               f"内存={metrics['memory_percent']}%, "
                               f"磁盘={metrics['disk_percent']}%,间隔：{settings.metrics_collection_interval}秒")
                    if settings.save_metrics_to_db and MetricsStorageService.save_metrics_to_db(metrics):
                        logger.info("系统监控数据，保存数据库成功")
            except Exception as e:
                logger.error(f"系统监控数据收集失败: {e}")
    
    def _cleanup_worker(self):
        """清理工作器"""
        logger.info("清理工作器已启动")
        
        while self._running:
            try:
                # 每小时执行一次清理
                current_time = datetime.now()
                
                # 每天凌晨3点执行深度清理
                if current_time.hour == 3 and current_time.minute < 1:
                    logger.info("执行深度清理任务")
                    
                    # 清理缓存中的系统监控数据
                    SystemMonitorService.cleanup_old_metrics(7)
                    
                    # 如果启用了数据库保存，清理数据库中的旧数据
                    if settings.save_metrics_to_db:
                        deleted_count = MetricsStorageService.cleanup_old_metrics(
                            settings.metrics_retention_days
                        )
                        logger.info(f"已清理数据库中 {deleted_count} 条旧监控数据")
                    
                    # 休眠1小时避免重复执行
                    time.sleep(3600)
                
                # 每分钟检查一次
                time.sleep(60)
                
            except Exception as e:
                logger.error(f"清理任务失败: {e}")
                time.sleep(300)  # 出错后休眠5分钟

# 全局后台任务服务实例
background_service = BackgroundTaskService()

def start_background_tasks():
    """启动后台任务"""
    background_service.start()

def stop_background_tasks():
    """停止后台任务"""
    background_service.stop()